import json
import subprocess
import time
from collections import defaultdict

import humps
from pyecharts import options as opts
from pyecharts.charts import Tree

echarts_init_opts = {
    "init_opts": opts.InitOpts(
        # animation_opts=opts.AnimationOpts(animation=False),
        js_host='./',
        width='5000px',
        height='50000px'
    )
}


class TreeBuild(object):
    def __init__(self):
        self.oid_map = {}
        self.tree = {'name': '1.3 | org', 'children': [], 'value': '1.3'}
        self.key_children = defaultdict(list)
        self.visited = set()
        self.value_translate_map = json.load(open('./oid-fields.json'))

    def read_translate(self):
        with open("./snmptranslate.txt", "r") as r:
            for line in r.readlines():
                line = line.replace('"', "").strip()
                splits = line.split('\t')
                self.oid_map[splits[-1]] = splits[-1] + '[' + splits[0] + '|' + self.translate(splits[0]) + "]"

    @classmethod
    def check_is_parent(cls, father, child) -> bool:
        left, _ = child.rsplit('.', 1)
        if left == father:
            return True
        return False

    def find_children(self, top_key):
        if top_key in self.visited:
            return
        self.visited.add(top_key)
        for (key, value) in self.oid_map.items():
            if self.check_is_parent(top_key, key):
                self.key_children[top_key].append(key)
                self.find_children(key)

    def reformat_for_echarts(self, top_key):
        changed = []
        for child in self.key_children[top_key]:
            children_changed = self.reformat_for_echarts(child)
            changed.append({'name': self.oid_map[child], 'children': children_changed, 'value': ""})
        return changed

    def run(self):
        self.read_translate()
        self.find_children('1.3')
        tree_data = {'name': "1.3", 'children': self.reformat_for_echarts('1.3')}
        print(json.dumps(tree_data, indent=1))
        # with open('echarts-data/echarts.json') as f:
        #     tree_data = json.loads(f.read())
        tree = Tree(**echarts_init_opts)
        # reference: https://juejin.cn/post/6844903996977610765
        # "type": "tree",
        # add this below: initialTreeDepth: [-1],
        tree.add("test", [tree_data])
        tree.render()
        time.sleep(0.3)
        subprocess.run(f'''sed 's|"type": "tree",|"type": "tree",initialTreeDepth: [-1],|g' -i render.html''', shell=True)

    def translate(self, value):
        translated = []
        for split in humps.decamelize(value).split('_'):
            value = self.value_translate_map.get(split, '') or split
            translated.append(value)
        return "".join(translated)


if __name__ == '__main__':
    TreeBuild().run()
    # print(TreeBuild().translate('fileSize'))
